package com.nec.recommend.module.system.controller;

import com.nec.recommend.auth.AuthUser;
import com.nec.recommend.config.annotation.ManageApi;
import com.nec.recommend.consts.TokenConst;
import com.nec.recommend.exception.ServiceException;
import com.nec.recommend.module.system.dto.TokenInfoDTO;
import com.nec.recommend.module.system.service.LoginService;
import com.nec.recommend.module.system.vo.LoginUserVO;
import com.nec.recommend.module.system.vo.UpdatePwdVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "1、登录功能接口")
@RestController
@RequestMapping("/")
public class LoginController {
    private final LoginService loginService;

    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    @ManageApi
    @ApiOperation("登录")
    @PostMapping("/login")
    public TokenInfoDTO login(@RequestBody @Validated LoginUserVO loginUser, HttpServletRequest request) {
        AuthUser authUser = loginService.login(loginUser, request);
        return new TokenInfoDTO(TokenConst.MANAGE + TokenConst.TOKEN_HEADER, TokenConst.TOKEN_PREFIX + authUser.getToken());
    }

    @ManageApi
    @ApiOperation("刷新token")
    @PostMapping("/refreshToken")
    public TokenInfoDTO refreshToken(HttpServletRequest request) {
        AuthUser authUser = loginService.refreshToken(request);
        return new TokenInfoDTO(TokenConst.MANAGE + TokenConst.TOKEN_HEADER, TokenConst.TOKEN_PREFIX + authUser.getToken());
    }

    @ManageApi
    @ApiOperation("修改密码")
    @PostMapping("/updatePwd")
    public Boolean logout(@RequestBody @Validated UpdatePwdVO updatePwdVO, HttpServletRequest request) {
        if (StringUtils.equals(updatePwdVO.getOldPwd(), updatePwdVO.getNewPwd())) {
            throw new ServiceException("新密码不能与旧密码一致");
        }
        return loginService.updatePwd(updatePwdVO, request);
    }

    @ManageApi
    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public Boolean logout(HttpServletRequest request) {
        loginService.logout(request);
        return true;
    }
}
